<?php

function real_ip()
{
	static $realip = null;
	if($realip !== NULL)
	{
		return $realip;
	}
	
	if(isset($_SERVER))
	{
		if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
		{
			$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
			
			foreach($arr as $ip)
			{
				$ip = trim($ip);
				if($ip != 'unknown')
				{
					$realip = $ip;
					break;
				}
			}
		}
		elseif(isset($_SERVER['HTTP_CLIENT_IP']))
		{
			$realip = $_SERVER['HTTP_CLIENT_IP'];
		}
		else 
		{
			if(isset($_SERVER['REMOTE_ADDR']))
			{
				$realip = $_SERVER['REMOTE_ADDR'];
			}
			else 
			{
				$realip = '0.0.0.0';
			}
		}
	}
	else 
	{
		if(getenv('HTTP_X_FORWARDED_FOR'))
		{
			$realip = getenv('HTTP_X_FORWARDED_FOR');
		}
		elseif(getenv('HTTP_CLIENT_IP'))
		{
			$realip = getenv('HTTP_CLIENT_IP');
		}
		else 
		{
			$realip = getenv('REMOTE_ADDR');
		}
	}
	
	preg_match("/[\d\.]{7,15}/", $realip,$onlineip);
	$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
	
	return $realip;
}


function read_static_cache($cache_name)
{
	if((DEBUG_MODE & 2) == 2)
	{
		return false;
	}
	
	static $result = array();
	if(!empty($result[$cache_name]))
	{
		return $result[$cache_name];
	}
	$cache_file_path = ROOT_PATH . '/temp/static_caches/' . $cache_name . '.php';
	if(file_exists($cache_file_path))
	{
		include_once($cache_file_path);
		$result[$cache_name] = $data;
		return $result[$cache_name];
	}
	else 
	{
		return false;
	}
}

function write_static_cache($cache_name,$caches)
{
	if((DEBUG_MODE & 2) == 2)
	{
		return false;
	}
	$cache_file_path = ROOT_PATH . '/temp/static_caches/' . $cache_name . '.php';
	$content = "<?php\r\n";
	$content .= "\$data = " . var_export($caches,true) . ";\r\n";
	$content .= "?>";
	file_put_contents($cache_file_path, $content,LOCK_EX);
}

function gd_version() 
{
	include_once(ROOT_PATH . 'includes/cls_image.php');
	return cls_image::gd_version();
}

function addslashes_deep($value)
{
	if(empty($value))
	{
		return $value;
	}
	else 
	{
		return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
	}
}

function ecs_header($string,$replace = true,$http_response_code = 0)
{
	if(strpos($string, '../upgrade/index.php') === 0)
	{
		echo '<script type="text/javascript">window.location.href="' .$string . '";</script>';
	}
	$string = str_replace(array("\r","\n"), array('',''), $string);
	
	if(preg_match('/^\s*location:/is', $string))
	{
//	echo $string;exit;
		@header($string."\n",$replace);
		exit();
	}
	if(empty($http_response_code) || PHP_VERSION < '4.3')
	{
		@header($string,$replace);
	}
	else 
	{
		@header($string,$replace,$http_response_code);
	}
}

function gzip_enabled()
{
	static $enabled_gzip = NULL;
	
	if($enabled_gzip === NULL)
	{
		$enabled_gzip = ($GLOBALS['_CFG']['enable_gzip'] && function_exists('ob_gzhandler'));
	}
	
	return $enabled_gzip;
}



